<?php
namespace App\Http\Controllers\Manage\Steam\Game;

use App\Ext\Common\UploadImage;
use App\Http\Controllers\Manage\CommonController;
use App\Model\Steam\SteamGame;
use App\Model\Steam\SteamGamePicture;


class SteamGamePictureController extends CommonController
{

    /**
     *
     * 获取指定游戏关联图片信息
     *
     * @param $id
     * @return mixed
     */
    public function index($id)
    {
        $data = SteamGame::find($id);
        if (!$data) {
            return redirect()->back()->with('error', '游戏ID不存在');
        }
        $gamePicture = [];
        $result = SteamGamePicture::where('game_id', $data->id)->get();
        foreach ($result as $key => $val) {
            $gamePicture[] = [
                'original' => $val->img_original,
                'name' => $val->img_name,
                'file' => $this->domain . $val->img_url,
                'delete' => route('manage.steam.game.picture.delete',['id' => $val->id]),
                'id' => $val->id,
            ];
        }
        $gamePicture = json_encode($gamePicture);
        # 表单元素
        $param = [
            'picture' => [
                'type' => 'multiFile',
                'col' => '12',
                'name' => '',
                'accept' => 'image',
                'upload' => route('manage.steam.game.picture.upload',['id' => $data->id]),
                'value' => $gamePicture,
                'max_size' => 2,
                'max_count' => 10
            ]
        ];
        $viewData = [];
        $viewData['title'] = '商品相册';
        $viewData['nav'] = $this->navTab('steam_game', 'picture', ['id' => $id]);
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = null;
        $viewData['form_method'] = null;
        $viewData['form_button'] = [
            'back' => [
                'name' => '返回游戏列表',
                'type' => 'button',
                'route' => route('manage.steam.game.resource.index')
            ]
        ];
        # 渲染视图
        return view('manage.form', $viewData);
    }



    /**
     * 上传图像文件接口
     *
     * 请求：
     * picture: 图片
     *
     * 返回：
     * error: 错误码
     * initialPreviewConfig: 操作成功之后返回的图像参数
     *
     * @return array json
     */
    public function upload()
    {
        $id = $this->request->input('id');
        $response = array();
        # 读取上传的临时文件
        if (!$this->request->hasFile('picture')) {
            $response['error'] = '没有接受到上传的文件';
            return response()->json($response);
        }
        $file = $this->request->file('picture');
        # 原始文件名
        $originalName = $file->getClientOriginalName();
        # 新文件名
        $fileName = time() . substr(mt_rand(), 5);
        $fileName = $fileName . '.' . $file->getClientOriginalExtension();
        # 验证图片大小
        $sizeMax = formatBytes($file->getMaxFilesize());
        $sizeMax = floor($sizeMax);
        $fileSize = formatBytes($file->getClientSize());
        if ($fileSize > $sizeMax) {
            $response['error'] = '文件"' . $originalName . '"容量为' . $fileSize . 'MB，超过上传文件大小限制，文件上传的最大限制为' . $sizeMax . 'MB';
            return response()->json($response);
        }
        # 验证图片格式
        $image = new UploadImage();
        $mime = ['jpg','jpeg','png']; # 文件类型限制
        if (!$image->checkMime($file, $mime)) {
            $response['error'] = '上传的文件格式限制为"jpg,jpeg,png"';
            return response()->json($response);
        }
        # 保存文件对象
        $imageParam = [
            'large' => ['w' => 1024, 'watermark' => $this->filePath['water_mark']],
            'middle' => ['w' => 350, 'watermark' => $this->filePath['water_mark']],
            'small' => ['w' =>64, 'h' => 64],
        ];
        $result = $image->save($file, $this->path['steam_game_picture'], $fileName, $imageParam);
        # 上传到云存储
        if ($result != false) {
            # 写入数据库
            $gamePicture = new SteamGamePicture();
            $gamePicture->game_id = $id;
            $gamePicture->img_url = $this->path['steam_game_picture'] . $fileName;
            $gamePicture->img_name = $fileName;
            $gamePicture->img_original = $originalName;
            $gamePicture->save();
            # 返回文件保存节点路径和相关参数
            $response['initialPreviewConfig'][] = [
                'caption' => $gamePicture->img_original,
                'url' => route('manage.steam.game.picture.delete',['id' => $gamePicture->id]),
                'key' => $gamePicture->id,
                'extra' => ['id' => $gamePicture->id],
            ];
            $response['initialPreview'][] = ['<img key="' . $gamePicture->id . '" src="' . $this->domain . $gamePicture->img_url . '" class="file-preview-image" alt="' . $gamePicture->img_original . '" title="' . $gamePicture->img_original . '">'];
        }
        return response()->json($response);
    }

    /**
     * 删除上传图像文件接口
     *
     * 请求：
     * token: 图片
     * file: 文件
     *
     * 返回：
     * error: 错误码
     * id: 删除成功之后重置的id
     *
     * @return array json
     */
    public function delete()
    {
        $id = $this->request->input('id');
        $response = array();
        # 读取商品图ID
        $gamePicture = SteamGamePicture::find($id);
        # 删除云存储对象
        # 删除图片
        $image = new UploadImage();
        $path = [
            $this->path['steam_game_picture'],
            $this->path['steam_game_picture'] . 'large/',
            $this->path['steam_game_picture'] . 'middle/',
            $this->path['steam_game_picture'] . 'small/',
        ];
        $image->delete($gamePicture->img_name, $path);
        # 删除商品图数据
        $gamePicture->delete();
        # 返回值
        $response['id'] = $id;
        return response()->json($response);
    }
}
